package com.itheima.request.param;

import com.itheima.request.domain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;

@WebServlet("/demo7")
public class ServletDemo7 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        Map<String, String[]> map = req.getParameterMap();
        User user = new User();
        Set<String> keys = map.keySet();
        try {
            for (String key : keys) {
                //key:username pwd hobby
                //通过属性描述符进行数据操作
                PropertyDescriptor pd = new PropertyDescriptor(key,User.class);
                Method writeMethod = pd.getWriteMethod();
                String [] values = map.get(key);
                //调用 这个属性的set方法，将数据设置到这个user对象上
                //判参数的类型，如果是String[] 我们要将values当成一个单独的对象传递
                //如果是String我们直接将valuse放着就行
                Class<?> cls = writeMethod.getParameterTypes()[0];
                if(cls==String.class){
                    writeMethod.invoke(user,values);
                }else if (cls==String[].class){
                    //如果需要传递一个数组对象，会被当作可变参数使用，将数组中的每一个元素当作参数传递
                    //这里需要将其转成Object，当成一个独立对象使用
                    writeMethod.invoke(user,(Object)values);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(user);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
